package org.example.bighomework.usercontrol;

import org.example.bighomework.Myuser.Myuser;
import org.example.bighomework.Myuser.MyuserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl  implements UserDetailsService {

    MyuserRepository service; // 用户信息CRUD服务类
    public UserDetailsServiceImpl(MyuserRepository service) {
        this.service = service;
    }

    @Override
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
        Optional<Myuser> optional = service.findById(id); // 根据username查询用户
        Myuser myuser = null;
        // 如果存在指定id
        if (optional.isPresent()) {
            // 从Optional对象中获取对象
            myuser = optional.get();

            // return new User(usr.getUsername(),usr.getPassword(), AuthorityUtils.NO_AUTHORITIES);


            List<GrantedAuthority> grantedAuthorities = new ArrayList();

            String roles=myuser.getRole();
            String[] roles_list=roles.split(",");  //数据库中角色都是用逗号,分隔的。
            for(String one:roles_list)
            {
                System.out.println("UserDetailsServiceImpl:one:"+one);
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(one);
                grantedAuthorities.add(grantedAuthority);
            }
            System.out.println("getPassword:"+myuser.getPassword());
            return new User(myuser.getId(),myuser.getPassword(),grantedAuthorities);

        } else {
            // 否则抛出运行时异常
            throw new UsernameNotFoundException("当前用户不存在！");
        }




    }
}
